package leetcode.weekly.week302;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//Solution3Test
public class Solution3 {
	
	public int[] smallestTrimmedNumbers(String[] nums, int[][] queries) {
		int len = queries.length, len1 = nums.length, len2 = nums[0].length();
		Map<Integer, List<int[]>> map = new HashMap<>();
		for (int i = 0; i < queries.length; i++) {
			int[] query = queries[i];
			int k = query[0], trim = query[1];
			List<int[]> list = map.getOrDefault(trim, new ArrayList<>());
			list.add(new int[] { k, i });
			map.put(trim, list);
		}
		int[] ans = new int[len];
		for (Map.Entry<Integer, List<int[]>> entry : map.entrySet()) {
			int trim = entry.getKey();
			List<int[]> anses = entry.getValue();
			String[][] numss = new String[len1][2];
			for (int i = 0; i < len1; i++) {
				String num = nums[i].substring(len2 - trim);
				numss[i][0] = num;
				numss[i][1] = String.valueOf(i);
			}
			Arrays.sort(numss, (a, b) -> a[0] != b[0] ? a[0].compareTo(b[0]) : a[1].compareTo(b[1]));
			for (int i = 0; i < anses.size(); i++) {
				int[] a = anses.get(i);
				ans[a[1]] = Integer.valueOf(numss[a[0] - 1][1]);
			}
		}
		return ans;
	}

}
